package com.example.chengww.myone.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * Created by chengww on 2016/9/19.
 */
public class HTTPUtils {

    public static InputStream getInputStream(String path){
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            if (connection.getResponseCode() == 200){
                return connection.getInputStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getStringByInputStream(InputStream inputStream){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String result = null;
        int len = 0;
        byte[] buf = new byte[1024];
        try{
            while((len = inputStream.read(buf)) != -1){
                out.write(buf,0,len);
            }
            out.flush();
            result = out.toString();
            out.close();
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static String URLDecode(String str){
        String result = null;
        try {
            result = URLDecoder.decode(str,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
